package com.sicnu.demo07.model

class CardMatchingGame(private val count: Int, private val matchingMode: Int = 2)  {
    var score = 0
        private set

    private var cards: MutableList<Card>

    init {
        cards = mutableListOf()
        initializeCards()
    }

    private fun initializeCards() {
        val deck = Deck()
        cards.clear()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun cardAtIndex(index: Int): Card {
        return cards[index]
    }

    val MISMATCH_PENALTY = 2
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    fun chooseCardAtIndex(index: Int) {
        val card = cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                // 收集已选中但未匹配的卡片
                val chosenCards = cards.filter { it.isChosen && !it.isMatched }
                
                when {
                    // 2张牌游戏模式
                    matchingMode == 2 && chosenCards.size == 1 -> {
                        val otherCard = chosenCards[0]
                        val matchScore = card.match(arrayOf(otherCard))
                        if (matchScore > 0) {
                            score += matchScore * MATCH_BONUS
                            otherCard.isMatched = true
                            card.isMatched = true
                        } else {
                            score -= MISMATCH_PENALTY
                            otherCard.isChosen = false
                        }
                    }
                    // 3张牌游戏模式
                    matchingMode == 3 && chosenCards.size == 2 -> {
                        val matchScore = card.match(chosenCards.toTypedArray())
                        if (matchScore > 0) {
                            score += matchScore * MATCH_BONUS
                            chosenCards.forEach { it.isMatched = true }
                            card.isMatched = true
                        } else {
                            score -= MISMATCH_PENALTY
                            chosenCards.forEach { it.isChosen = false }
                        }
                    }
                    // 已选中的卡片数量超过阈值，取消所有已选中的卡片
                    chosenCards.size >= matchingMode -> {
                        chosenCards.forEach { it.isChosen = false }
                    }
                }
                
                score -= COST_TO_CHOOSE
                card.isChosen = true
            }
        }
    }
    
    fun reset() {
        score = 0
        initializeCards()
    }
}
